package com.ewei.web.crawler.utils;

import java.util.Map;
import java.util.Map.Entry;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.Connection.Method;

public class ConnectionHandler {
	private static final String DEFAULT_CONNECTION = "keep-alive";
	private static final String DEFAULT_ACCEPT_ENCODING = "gzip,deflate,sdch";
	private static final String DEFAULT_USERAGENT = "Mozilla";
	private static final String DEFAULT_ACCEPT = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
	private static final String CONTENT_TYPE = "application/x-www-form-urlencoded;charset=UTF-8";
	private static final int DEFAULT_TIMEOUT = 8000;
	private ConnectionHandler(){
	}
	/**
	 *use the default configuration
	 *
	 */
	public static Connection wrapper(Connection conn){
		return 
			 conn
			.userAgent(DEFAULT_USERAGENT)
			.header("Accept-Encoding",DEFAULT_ACCEPT_ENCODING)
			.header("Accept", DEFAULT_ACCEPT)
			.header("Connection",DEFAULT_CONNECTION)
			.header("Content-Type",CONTENT_TYPE)
			.timeout(DEFAULT_TIMEOUT)
			;
	}
	/**
	 * wrap with host
	 * @param conn
	 * @param hostName
	 * @return
	 */
	public static Connection wrapper(Connection conn,String hostName){
		return wrapper(conn).header("Host",hostName);
	}
	/**
	 * wrap with specific configuration
	 * @param conn
	 * @param config
	 * @return
	 */
	public static Connection wrapper(Connection conn,Map<String,String> config){
		for(Entry<String,String> entry: config.entrySet()){
			conn.header(entry.getKey(),entry.getValue());
		}
		return null;
	}
}
